<template>
  <div class="login w100 h100">
    <vue-scroll>
      <div class="platform-name">
        <div class="cn">{{platformCn}}</div>
        <div class="en">{{platformEn}}</div>
      </div>
      <div class="form-container">
        <img src="../../../static/image/login/pc.png" alt="">
        <el-form label-width="80px" :model="loginForm" :rules="rules"  ref="loginForm" class="login-form">
          <img src="../../../static/image/login/light.png" alt="" class="light top">
          <img src="../../../static/image/login/light.png" alt="" class="light bottom">
          <el-form-item class="username" prop="username">
            <el-input v-model="loginForm.username" placeholder="用户名" @keyup.enter.native="login('loginForm')">
              <img slot="prefix" src="../../../static/image/login/username.png">
              <span class="vertical-line" slot="prefix"></span>
            </el-input>
          </el-form-item>
          <el-form-item class="password" prop="password">
            <el-input type="password" v-model="loginForm.password" placeholder="密码" @keyup.enter.native="login('loginForm')">
              <img slot="prefix" src="../../../static/image/login/password.png">
              <span class="vertical-line" slot="prefix"></span>
            </el-input>
          </el-form-item>
          <div style="text-align: right">
            <el-checkbox v-model="rememberPass" class="remember-pass">记住密码</el-checkbox>
          </div>
          <el-button type='primary' class="login-btn" @click="loginValidate('loginForm')">
            <span style="margin-right: 22px">登</span> 录
          </el-button>
        </el-form>
      </div>
    </vue-scroll>
  </div>
</template>

<script>
  import { mapMutations } from 'vuex'
  let Base64 = require('js-base64').Base64
  import Config from '../../config'
  import { createTreeData } from '../../util/tree'
  export default {
    name: 'Login',
    data () {
      return {
        loginForm: {
          username: '',
          password: ''
        },
        rememberPass: false,
        REMEMBER_DAYS: 7,
        rules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' }
          ]
        },
        platformCn: Config.PLATFORM_CN,
        platformEn: Config.PLATFORM_EN,
      }
    },
    mounted () {
      this.getCookie()
    },
    methods: {
      ...mapMutations('user', [
        'setUser',
        'setRole',
        'setDistrict',
        'setModule',
        'setButton'
      ]),
      /**
       * 表单验证
       * @param {String} val
       * */
      loginValidate (val) {
        this.$refs[val].validate((valid) => {
          if (valid) {
            this.login()
          } else {
            this.$message(
              {
                message: '账号和密码不能为空',
                type: 'warning'
              }
            )
            return false
          }
        })
      },
      /**
       * 登录
       * */
      login () {
        const url = `${Config.AUTH_URL}/login?user=${this.loginForm.username}&key=${this.loginForm.password}&type=2&systemId=7`
        this.$http.post(url)
          .then(data => {
            // console.log(data)
            const role = data.role
            const ROLE_COMMUNITY = 0
            if (role[0].sort < ROLE_COMMUNITY) { // 平台最小的角色是0，场所管理员
              this.$message.warning('当前用户不允许在平台登录')
              return
            }
            sessionStorage.setItem('token', data.token)
            // 存储user到vuex
            if (data.userDetail) {
              data.user.company = data.userDetail.company
            }
            this.setUser(data.user)
            this.setRole(data.role)
            this.setDistrict(data.distrcat)
            if (this.rememberPass) {
              this.setCookie(this.loginForm.username, this.loginForm.password, this.REMEMBER_DAYS)
            } else {
              this.clearCookie()
            }
            this.getButtonByRoles()
              .then(() => {
                this.getModuleById()
                  .then(res => {
                    this.$router.push({
                      path: '/'
                    })
                  })
              })
          })
          .catch(e => {
            this.$message.warning('账户或密码不正确')
          })
        // console.log(this.loginForm)
      },
      /**
       * 设置cookie
       * */
      setCookie (username, password, exdays) {
        const exdate = new Date() //获取时间
        exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays) //保存的天数
        //字符串拼接cookie
        window.document.cookie = "Username" + "=" + Base64.encode(username) + ";path=/;expires=" + exdate.toGMTString();
        window.document.cookie = "Password" + "=" + Base64.encode(password) + ";path=/;expires=" + exdate.toGMTString();
      },
      /**
       * 获取cookie
       * */
      getCookie () {
        if (document.cookie.length > 0) {
          var arr = document.cookie.split('; ') //这里显示的格式需要切割一下自己可输出看下
          for (var i = 0; i < arr.length; i++) {
            var arr2 = arr[i].split('=') //再次切割
            //判断查找相对应的值
            if (arr2[0] == 'Username') {
              this.loginForm.username = Base64.decode(arr2[1]) //保存到保存数据的地方
              this.rememberPass = true // 如果从cookie中获取到用户名，密码，name将记住密码置为true
            } else if (arr2[0] == 'Password') {
              this.loginForm.password = Base64.decode(arr2[1])
            }
          }
        }
      },
      /**
       * 清除cookie中用户名，密码
       * */
      clearCookie () {
        this.setCookie('', '', -1) //修改2值都为空，天数为负1天就好了
      },
      /**
       * 根据用户id获取模块树
       * @return {Promise}
       * */
      getModuleById () {
        return new Promise((resolve, reject) => {
          const url = `${Config.AUTH_URL}/auth/getMenuByUserId`
          this.$http.get(url)
            .then(data => {
              this.setModule(data)
              // console.log('******** ', data)
              resolve()
            })
            .catch(e => reject(e))
        })
      },
      /**
       * 获取用户所有的按钮
       * */
      getButtonByRoles () {
        return new Promise((resolve, reject) => {
          const url = `${Config.AUTH_URL}/getButtonByRoles`
          this.$http.get(url)
            .then(data => {
              this.setButton(data)
              // console.log(data)
              resolve()
            })
            .catch(e => reject(e))
        })
      },
    }
  }
</script>

<style lang="scss" scoped>
  .login {
    background-image: url("../../../static/image/login/login-bg.png");
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-position: center center;
    background-size: cover;
    .platform-name {
      font-weight:bold;
      margin-top: 138px;
      text-align: center;
      .cn {
        font-size: 60px;
        color: #F4F4F4;
        background:linear-gradient(0deg, #519BFC 0%, #fff 100%);
        -webkit-background-clip:text;
        -webkit-text-fill-color:transparent;
        margin-bottom: 39px;
      }
      .en {
        font-size: 28px;
        color: #B3D8F8;
        background:linear-gradient(0deg, #519BFC 0%, #fff 100%);
        -webkit-background-clip:text;
        -webkit-text-fill-color:transparent;
        letter-spacing: 16px;
      }
    }
    .form-container {
      position: relative;
      width: 1235px;
      min-height: 53%;
      margin: 41px auto 0 auto;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      img {
        width: auto;
        height: 361px;
        margin: 112px 269px 0 18px;
      }
      .login-form {
        width: 409px;
        border: 1px solid #3254c5;
        height: 100%;
        background: #112464;
        opacity: 0.8;
        border-radius:6px;
        box-sizing: border-box;
        padding: 124px 42px 95px 42px;
        position: relative;
        .light {
          width: auto;
          height: 23px;
          position: absolute;
          left: 90px;
        }
        .top {
          top: -124px;
        }
        .bottom {
          bottom: -11px;
        }
        .username {
          margin-bottom: 39px;
          position: relative;
        }
        .password {
          margin: 39px 0 31px 0;
          position: relative;
        }
        .remember-pass {
          margin-bottom: 77px;
          color: #69A9FF;
          /deep/ .el-checkbox__input.is-checked .el-checkbox__inner, .el-checkbox__input.is-indeterminate .el-checkbox__inner {
            background-color: #69A9FF;
            border-color: #69A9FF;
          }
          /deep/ .el-checkbox__inner {
            background-color: transparent;
            border-color: #278DFF;
          }
          /deep/ .el-checkbox__inner:hover {
            border-color: #69A9FF;
          }
        }
        .login-btn {
          width: 100%;
          height: 42px;
          font-size: 18px;
          text-align: center;
          background:linear-gradient(0deg, #278dff, #2bd8fd);
          border-radius:4px;
          outline: none;
          border-color: #278DFFFF;
          &:active, &:hover {
            background:linear-gradient(0deg,rgba(39,141,255,1),rgba(43,216,253,1));
          }
        }
      }
      .login-form /deep/ .el-form-item__content {
        margin-left: 0 !important;
        img {
          width: 15px;
          height: auto;
          margin: 0 21px;
        }
        .vertical-line {
          display: inline-block;
          width: 1px;
          height: 15px;
          background-color: #69A9FF;
          margin-right: 15px;
        }
        .el-input__inner {
          padding-left: 77px;
          border-color: #278DFF;
          background: rgba(39,141,255,0.1);
          color: #fff;
          &:focus {
            border-color: #278DFF;
          }
        }
        ::-webkit-input-placeholder { /* WebKit, Blink, Edge */
          color: #69A9FF;
        }
        :-moz-placeholder { /* Mozilla Firefox 4 to 18 */
          color: #69A9FF;
        }
        ::-moz-placeholder { /* Mozilla Firefox 19+ */
          color: #69A9FF;
        }
        :-ms-input-placeholder { /* Internet Explorer 10-11 */
          color: #69A9FF;
        }
      }
    }
  }
</style>
